package com.cjym.GateWay.interfaces.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.cjym.GateWay.interfaces.TokenAuth;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import java.util.Set;

@Component
@Slf4j
public class DefaultTokenAuthImpl implements TokenAuth {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${gateway.token.name:#{'token'}}")
    private String tokenName;
    @Override
    public boolean tokenAuth(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(tokenName);
        log.info("request token = {}", token);
        //判断路径
        String value = request.getPath().value();
        log.info("request path value = {}", value);
        //判断是否为登录请求
        String s = request.getURI().toString();
        log.info("url = {}", s);
        Set<String> members = stringRedisTemplate.opsForSet().members("nulltoken::router");
        if (!ObjectUtils.isEmpty(members)&&members.contains(value)) {
            log.info("已放行的 value = {}", value);
            return true;
        } else {
            if (!StringUtils.isEmpty(token)) {
                log.info("token = {}", token);
                //从数据库中判断token是否合法
                token = stringRedisTemplate.opsForValue().get(token);
                log.info("用户信息为 = {}", token);
                return !StringUtils.isEmpty(token);
            }
        }
        return false;
    }
}
